package com.team.controller;

import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

import static cn.hutool.core.img.ImgUtil.toBufferedImage;

@Controller
public class CaptchaController {
    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request,HttpServletResponse response) throws IOException {
        CaptchaUtil.out(request, response);
    }
    @RequestMapping("/captcha2")
    public void getShearCaptcha(HttpServletResponse response){
        //定义图形验证码的长，宽，验证码字符数，干扰线宽度
        ShearCaptcha shearCaptcha= cn.hutool.captcha.CaptchaUtil.createShearCaptcha(100,50,4,3);
        //设置背景颜色
        shearCaptcha.setBackground(new Color(210,111,234));
        //生成四位验证码
        String code= RandomUtil.randomNumbers(4);
        //生成验证码图片
        Image image=shearCaptcha.createImage(code);
        //返回验证码信息
        responseCode(response,code,image);
    }
    private static void responseCode(HttpServletResponse response, String code, Image image) {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        String uuidStr = UUID.randomUUID().toString().replace("-", "");
        System.out.println("uuidStr:" + uuidStr);
//        log.info("生成验证码 uuidStr：{} ，code:{}",uuidStr, code);
        response.setHeader("verifyCodeUuid",uuidStr);
        try {
            BufferedImage bufferedImage = toBufferedImage(image);
            // 创建一个ByteArrayOutputStream，用于存储图片数据
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 写入图片数据到ByteArrayOutputStream
            ImageIO.write(bufferedImage, "jpeg", baos);
            // 将ByteArrayOutputStream转换为ByteArrayInputStream
            byte[] imageInBytes = baos.toByteArray();
            //输出
            IoUtil.write(response.getOutputStream(), true, imageInBytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
